<template>
  <div>
    <div class="search">
      <input type="text" placeholder="请输入所选城市" class="search-input" v-model="keyword" ref="search">
    </div>
    <div class="search-content" ref="content" v-show="keyword">
      <ul>
        <li
          class="search-content-info border-bottom"
          v-for="item in list"
          :key="item.id"
          @click="handleCityClick(item.name)"
        >{{ item.name }}</li>
        <li class="search-content-info" v-show="hasNoData">没有相关数据</li>
      </ul>
    </div>
  </div>
</template>
<script>
import Bscroll from "better-scroll";
export default {
  props: {
    cities: Object
  },
  data() {
    return {
      keyword: "",
      timer: null,
      list: []
      // flag: false
    };
  },
  methods: {
    handleCityClick(city) {
      this.$store.commit("changeCity", city);
      this.$router.push("/");
    }
  },
  watch: {
    keyword() {
      if (this.timer) {
        clearTimeout(this.timer);
      }
      if (!this.keyword) {
        this.list = [];
        return;
      }
      this.timer = setTimeout(() => {
        let result = [];
        for (var i in this.cities) {
          this.cities[i].forEach(item => {
            if (
              item.name.indexOf(this.keyword) > -1 ||
              item.spell.indexOf(this.keyword) > -1
            ) {
              result.push(item);
            }
          });
        }
        this.list = result;
      }, 50);
    }
  },
  mounted() {
    this.scroll = new Bscroll(this.$refs.content);
  },
  computed: {
    hasNoData() {
      return !this.list.length;
    }
  }
};
</script>
<style lang="stylus" scoped>
@import '~styles/varibles.styl';

.border-bottom::before {
  background-color: #eee;
}

.search {
  background-color: $bgColor;
  padding: 0.1rem;
  height: 0.72rem;

  .search-input {
    box-sizing: border-box;
    height: 0.62rem;
    line-height: 0.62rem;
    width: 100%;
    color: #666;
    border-radius: 0.06rem;
    padding: 0.02rem;
    text-align: center;
  }
}

.search-content {
  z-index: 1;
  position: absolute;
  overflow: hidden;
  top: 1.78rem;
  right: 0;
  left: 0;
  bottom: 0;
  background-color: #fff;

  .search-content-info {
    padding: 0.1rem;
    text-indent: 0.2rem;
  }
}
</style>